package com.it.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.aiReportClaim.ReportClaimApi;
import com.it.entity.closure.AiClaimClosure;
import com.it.mapper.AiClaimClosureMapper;
import com.it.service.AiClaimClosureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.R;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  理赔结案信息表（理赔全流程结束后的最终记录） 服务实现类
 * </p>
 *
 * @author lutao
 * @since 2025年09月24日
 */
@Service
public class AiClaimClosureServiceImpl extends ServiceImpl<AiClaimClosureMapper, AiClaimClosure> implements AiClaimClosureService {

    @Autowired
    private AiClaimClosureMapper aiClaimClosureMapper;

    @Autowired
    private ReportClaimApi reportClaimApi;
    @Override
    public R list(Integer pageNum, Integer pageSize, String closureId, Integer closureType) {
        PageHelper.startPage(pageNum, pageSize);
//        LambdaQueryWrapper<AiClaimClosure> queryWrapper = new LambdaQueryWrapper<>();
//        if(StringUtils.isNotBlank(closureId)){
//            queryWrapper.eq(AiClaimClosure::getClosureId, closureId);
//        }
//        if(closureType != null){
//            queryWrapper.eq(AiClaimClosure::getClosureType, closureType);
//        }
//        List<AiClaimClosure> list = aiClaimClosureMapper.selectList(queryWrapper);
        List<AiClaimClosure> list = aiClaimClosureMapper.list(closureId,closureType);
        PageInfo<AiClaimClosure> pageInfo = new PageInfo<>(list);
        return  R.Success("查询成功",pageInfo);
    }

    @Override
    @Transactional
    public R insert(AiClaimClosure aiClaimClosure) {
        aiClaimClosure.setClosureId(generatePolicyNo());
        aiClaimClosureMapper.insert(aiClaimClosure);
        // 调用reportClaimApi更新状态
        reportClaimApi.updateStatus(aiClaimClosure.getReportNo(), 8);
        return R.Success("新增成功", aiClaimClosure);
    }




    /**
     * 生成结案编号
     * 格式：CLS+yyyyMMdd+6位随机数，例如：CLS20250918123456
     */
    private String generatePolicyNo() {
        // 前缀
        String prefix = "CLS";
        // 日期部分：年月日
        String datePart = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 随机数部分：6位随机数
        String randomPart = String.format("%06d", new Random().nextInt(1000000));

        // 组合生成保单编号
        return prefix + datePart + randomPart;
    }
}
